package org.web.webdisplay.server.config;

import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionManager;


import javax.sql.DataSource;

@Configuration("webDisplayServerDBConfig")
@MapperScan(basePackages = "org.web.webdisplay.server.dao", sqlSessionFactoryRef = "webDisplayServerSqlSessionFactory")
public class WebDisplayServerDBConfig {

    @Bean("webDisplayServerDataSource")
    @ConfigurationProperties(prefix = "org.web.webdisplay.server.jdbc")
    public DataSource getDataSource() {
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setMaximumPoolSize(30);
        dataSource.setMinimumIdle(30);
        return dataSource;
    }

    @Bean("webDisplayServerSqlSessionFactory")
    public SqlSessionFactory getSqlSessionFactory(@Qualifier("webDisplayServerDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/WebDisplayServer/Mapper*.xml"));
        return sessionFactory.getObject();
    }

    @Bean("webDisplayServerTransactionManager")
    public TransactionManager getTransactionManager(@Qualifier("webDisplayServerDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

}
